<template>
  <view class="history-container">
    <view class="content">
      <!-- 空状态 -->
      <view
        v-if="
          !historyStore.processedHistory || historyStore.processedHistory.length === 0
        "
        class="empty-state"
      >
      </view>
      <!-- 历史对话列表 -->
      <view v-else class="history-list">
        <view
          v-for="(item, index) in historyStore.processedHistory"
          :key="index"
          class="history-item-wrapper"
          @longpress="showDeleteMenu(item.chatId)"
        >
          <view class="history-item" @click="openChat(item.chatId)">
            <image
              class="avatar"
              :src="getAvatarPath(index)"
              mode="aspectFill"
            ></image>
            <view class="item-content">
              <view class="item-title u-line-1">{{ item.title }}</view>
              <view class="item-time">{{ item.firstMessageTime }}</view>
            </view>
          </view>
          <view class="divider-line"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onMounted } from "vue";
import { useHistoryStore } from "@/store/modules/chat/history";
import { useChatStore } from "@/store/modules/chat/chat";
const historyStore = useHistoryStore();
const chatStore = useChatStore();

onMounted(() => {
  historyStore.fetchHistoryList();
  
  // 添加提示：首次进入页面时显示长按删除提示
  const hasShownTip = uni.getStorageSync('hasShownLongPressTip');
  if (!hasShownTip && historyStore.processedHistory?.length > 0) {
    setTimeout(() => {
      uni.showToast({
        title: '长按可删除对话',
        icon: 'none',
        duration: 2000
      });
      uni.setStorageSync('hasShownLongPressTip', true);
    }, 1000);
  }
});

// 计算头像图片路径
const getAvatarPath = (index) => {
  const imageIndex = (index % 3) + 1;
  return `/static/wlxzstytle/前缀图${imageIndex}.png`;
};

// 打开指定对话
const openChat = (chatId) => {
  chatStore.clearMessages();
  console.log("历史对话id" + chatId);
  // 传递 params 的意义在于将 chatId 作为参数传递给目标页面 "/pages_chat/pages/chat/index"，
  // 目标页面可以通过获取该参数来知晓用户要打开的具体对话，从而加载对应对话的内容。
  uni.$u.route({
    url: "/pages_chat/pages/chat/index",
    params: { chatId },
  });
};

// 显示删除菜单（长按触发）
const showDeleteMenu = (chatId) => {
  uni.showActionSheet({
    itemList: ['删除对话'],
    itemColor: '#ff4d4f',
    success: (res) => {
      if (res.tapIndex === 0) {
        deleteChat(chatId);
      }
    },
    fail: (res) => {
      console.log(res.errMsg);
    }
  });
};

// 删除对话
const deleteChat = async (chatId) => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条历史对话吗？删除后将无法恢复。",
    confirmColor: "#ff4d4f",
    success: async (res) => {
      if (res.confirm) {
        try {
          await historyStore.removeHistoryChat(chatId);
          uni.showToast({
            title: "删除成功",
            icon: "success",
          });
        } catch (error) {
          uni.showToast({
            title: "删除失败",
            icon: "error",
          });
        }
      }
    },
  });
};
</script>

<style lang="scss" scoped>
.history-container {
  min-height: 100vh;
  background-color: white;
}

.content {
  padding: 20rpx;
}

.empty-state {
  padding: 200rpx 0;
}

.history-list {
  .history-item-wrapper {
    /*   display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    background: #fff;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1); */

    .history-item {
      display: flex;
      align-items: center;
      padding: 30rpx;

      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        flex-shrink: 0;
      }

      .item-content {
        flex: 1;
        min-width: 0;
        
        .item-title {
          font-size: 32rpx;
          color: #333;
          font-weight: 500;
          margin-bottom: 10rpx;
        }

        .item-time {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .delete-btn {
      width: 120rpx;
      height: 100%;
      background: #ff4d4f;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: background-color 0.3s;

      &:active {
        background: #ff7875;
      }

      .delete-text {
        color: #fff;
        font-size: 28rpx;
      }
    }

    .divider-line {
      width: 100%;
      height: 1rpx;
      background-color: rgba(247, 247, 247, 1);
      margin: 0;
    }
  }
}

.item-arrow {
  flex-shrink: 0;
}
</style>
